from BeautifulSoup import BeautifulSoup
import urllib2
import urllib
import string


class AlbumArtOrgSoup:
    
    url = "http://www.albumart.org/index.php?srchkey=%s+&itempage=1&newsearch=1&searchindex=Music"
    tag = "a"
    property = "href"
    args = ()
    kwargs = {}
    covers = []
    
    def __init__(self, tag = None, property = None, *args, **kwargs):
        if tag:
            self.tag = tag
        if property:
            self.property = property
        
        if args:
            self.args = args
        
        if kwargs:
            self.kwargs = kwargs
    
    def generate_url(self, query):
        """ returns the url that AlbumArtOnline will download """
        return self.url % (query)
    
    def set_url(self, url):
        """ manipulate the url used to get the covers"""
        if url:
            self.url = url
    
    def search(self, soup):
        """ use BeautifulSoup to filter out the html tags containing the urls to the covers"""
        
        list = soup.findAll(self.tag, *self.args, **self.kwargs)
        for a in list:
            
            prop = a.get(self.property)
            
            # don't add a url twice
            if prop and not prop in self.covers:
                self.covers.append(prop)
        
        return self.covers
            

class AlbumArtOnline:
    """ Retrieves urls to covers found via the passed SearchClass """
    
    
    query = ""
    covers = []
    __pagehandle = None
    __html = ""
    __tree = None
    __SearchClass = None
    __soup = None
    
    def __init__(self, query, SearchClass):
        self.query = query
        self.__SearchClass = SearchClass
        
        self.__load_html()
        self.__parse_html()
        
    def __load_html(self):
        """ load html page with searched images into cache """
        
        # get the url from the SearchClass
        url = self.__SearchClass.generate_url(urllib.quote_plus(self.query))
        try:
            self.__pagehandle = urllib2.urlopen(url)
        except urllib2.URLError:
            ### TODO: do some errorhandling instead of failing silently
            return
        self.__html = self.__pagehandle.read()
    
    def __parse_html(self):
        # parse the html tree with BeautifulSoup
        self.__parse_html = BeautifulSoup(self.__html)
        
        # let the SearchClass do its job
        self.covers = self.__SearchClass.search(self.__parse_html)
    
    
    def get_covers(self):
        return self.covers

if __name__ == "__main__":
    
    ### example:
    #
    # "a" is the tag that contains the url we search
    # "href": the url is saved as the 'href' property of the <a> tag
    # {"title": "View larger image"}: specifies the <a> tags, that we search
    #   because there are plenty of them =)
    soup = AlbumArtOrgSoup("a", "href", {"title": "View larger image"})
    
    # and now we will search for the album ...And Justice for All. You don't need
    # to escape or quote this string, as this gets done internally.
    albumart = AlbumArtOnline("and justice for all", soup)
    
    # if everythin went well you'll find here all the urls to possible album covers
    covers = albumart.get_covers()
    
    print "covers:"
    for cover in covers:
        print cover